package com.wteam.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wteam.PoJo.DTO.goods;
import com.wteam.PoJo.DTO.goods_collection;
import com.wteam.PoJo.DTO.goods_type;
import com.wteam.PoJo.DTO.memberdto;
import com.wteam.PoJo.VO.pageGoods;
import com.wteam.PoJo.VO.shopingvo;
import com.wteam.config.JWT.jwt;
import com.wteam.mapper.GoodsCollectionmapper;
import com.wteam.mapper.GoodsTypemapper;
import com.wteam.mapper.Goodsmapper;
import com.wteam.mapper.Memberdtomapper;
import com.wteam.service.GoodsService;
import com.wteam.untils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class Goodserviceimpl implements GoodsService {
    @Autowired
    private Memberdtomapper memberdtomapper;
    @Autowired
    private GoodsTypemapper goodsTypemapper;
    @Autowired
    private Goodsmapper goodsmapper;
    @Autowired
    private GoodsCollectionmapper goodsCollectionmapper;
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @CachePut(value = "goods_type", key = "#goodsType.id")
    public Result addGoodsType(goods_type goodsType) {
        LambdaQueryWrapper<goods_type> qw = new LambdaQueryWrapper<>();
        qw.eq(goods_type::getName, goodsType.getName());
        Long a = goodsTypemapper.selectCount(qw);
        if (a != 0
        ) {
            log.info(goodsTypemapper.selectCount(qw).toString());
            return Result.error("该类型已存在");
        } else {
            int insert = goodsTypemapper.insert(goodsType);
            if (insert == 1) {
                return Result.success();
            } else {
                return Result.error("添加失败，请联系管理员");
            }
        }
    }

    @Override
    public Result saveGoods(shopingvo shopingvo) {
        goods goods = new goods();
        BeanUtils.copyProperties(shopingvo, goods);
        log.info(goods.toString());
        LambdaQueryWrapper<goods_type> qw = new LambdaQueryWrapper();
        qw.eq(goods_type::getId, shopingvo.getGoodsType());
        Long aLong = goodsTypemapper.selectCount(qw);
        if (aLong == 0) {
            return Result.error("该分类找不到");
        }
        int insert = goodsmapper.insert(goods);
        return insert == 1 ? Result.success() : Result.error("插入失败");
    }

    @Override
    public List<goods_type> select() {

        LambdaQueryWrapper<goods_type> qw = new LambdaQueryWrapper();
        qw.select(goods_type::getId, goods_type::getName);
        List<goods_type> goods_types = goodsTypemapper.selectList(qw);
        return goods_types;

    }

    @Override
    public List<goods> pagelistgoods(pageGoods pageGoods) {
        log.info("传入参数{}" + pageGoods.toString());
        IPage<goods> iPage = new Page<>(pageGoods.getPage(), pageGoods.getPagesize());

        LambdaQueryWrapper<goods> qw = new LambdaQueryWrapper();
        qw.eq(pageGoods.getTypeId() != null, goods::getGoodsType, pageGoods.getTypeId());
        goodsmapper.selectPage(iPage, qw);
        List<goods> list = iPage.getRecords();
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result SaveCollectGoods(Integer goodId) {

        log.info("{}收藏商品id" + goodId);
        goods_collection goods_collection = new goods_collection();
        goods_collection.setGoodsId(goodId);

        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");
        String key = "goods_collect_" ;
        redisTemplate.delete(key);
        goods_collection.setMemberId(memberId);
        LambdaQueryWrapper<goods_collection> qw = new LambdaQueryWrapper();
        qw.eq(com.wteam.PoJo.DTO.goods_collection::getGoodsId, goodId)
                .eq(com.wteam.PoJo.DTO.goods_collection::getMemberId, memberId);
        final Long aLong = goodsCollectionmapper.selectCount(qw);
        if (aLong != 0) {
            return Result.error("该商品已收藏");
        }
        //给用户加积分
        memberdto memberdto = memberdtomapper.selectById(memberId);
        memberdto.setPoint(memberdto.getPoint() + 1000);
        memberdtomapper.updateById(memberdto);
//        @CacheEvict(value = "goods_collect", allEntries = true)

        return goodsCollectionmapper.insert(goods_collection) == 1 ? Result.success() : Result.error("收藏失败");
    }

    @Override
    public Result deleteCollectGoods(List<Integer> ids) {

        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");
        String key = "goods_collect_" ;
        redisTemplate.delete(key);
        for (Integer id : ids) {
            LambdaQueryWrapper<goods_collection> qw = new LambdaQueryWrapper();
            qw.eq(goods_collection::getGoodsId, id)
                    .eq(goods_collection::getMemberId, memberId);
            goodsCollectionmapper.delete(qw);
        }

        return Result.success();
    }

    @Override
    public Result listCollectGoods(Integer page, Integer pagesize) {


        Map<String, Object> claims = jwt.parseJWT(httpServletRequest.getHeader("token"));
        Integer memberId = (Integer) claims.get("id");
        //看有没有缓存
        String hashkey = memberId + "_" + page + "_" + pagesize;
        List<goods> listgoods1 = (List<goods>)  redisTemplate.opsForHash().get("goods_collect_", hashkey);
        if (listgoods1 != null && listgoods1.size() != 0) {
            return Result.success(listgoods1);
        }

        IPage<goods_collection> iPage = new Page<>(page, pagesize);
        LambdaQueryWrapper<goods_collection>lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(goods_collection::getMemberId,memberId);
        IPage<goods_collection> collectionIPage = goodsCollectionmapper.selectPage(iPage, lambdaQueryWrapper);
        List<goods_collection> list = collectionIPage.getRecords();
        List<goods> listgoods = new ArrayList<>();
        for (goods_collection goods_collection : list) {
            Integer goodsId = goods_collection.getGoodsId();
            LambdaQueryWrapper<goods> qw1 = new LambdaQueryWrapper();
            qw1.eq(goods::getId, goodsId);
            goods goods = goodsmapper.selectOne(qw1);
            listgoods.add(goods);

        }
        redisTemplate.opsForHash().put("goods_collect_",hashkey,listgoods);
        return Result.success(listgoods);
    }

    @Override
    public Result<goods> OneGoods(Integer id) {

        return Result.success(goodsmapper.selectById(id));

    }


}
